import { cmdInvoker } from '@amcax/base';
import { nmAppErrorLog } from '@app-nextmesh/common/utils';
import { CommandDialog2 } from '@app-nextmesh/components/Dialogs';
import { documentV2 } from '@app-nextmesh/domain';
import {
  ENTITY_TYPES,
  IMeshSize,
  ModelEventType,
  ModelPickTypesEvent,
  NMMeshGenCmdDialogParams,
} from '@app-nextmesh/types';
import { events } from '@app-nextmesh/utils';
import { RJSFSchema, UiSchema } from '@rjsf/utils';
import { useEffect, useState } from 'react';
import { SelectedEntitiesSchema, SizeSchema } from '../jsonSchema';
import { cmdSeed } from './cmd-seed';
import { MeshDialogFooter } from './MeshDialogFooter';

const schema: RJSFSchema = {
  type: 'object',
  properties: {
    ...SizeSchema,
    ...SelectedEntitiesSchema,
  },
};
export default function BaseGenerateDialog({
  title,
  type,
  onClose,
}: NMMeshGenCmdDialogParams<IMeshSize>) {
  const [formData, setFormData] = useState<IMeshSize>(null);
  const [loading, setLoading] = useState(false);
  const { invokeCmd } = cmdInvoker;

  const meshingDim = ['0d', 'lineMesh', 'general2D', 'tetMesh'].indexOf(type);
  const pickTypes = [ENTITY_TYPES[meshingDim]];

  useEffect(() => {
    // 设置当前支持的拾取类型
    events.emit(ModelEventType.PickTypes, {
      types: pickTypes,
    } as ModelPickTypesEvent);
  }, []);
  const submit = async (data) => {
    if (data) {
      data['MeshingDim'] = meshingDim;
      setFormData(data);
      setLoading(true);
      try {
        await documentV2.generateMesh(type, data);
        return true;
      } catch (error) {
        nmAppErrorLog('cmd-mesh-generate', 'onSubmit', error);
      } finally {
        setLoading(false);
      }
    }
    return false;
  };
  const onSubmit = async (data) => {
    if (await submit(data)) {
      onClose();
      if (type === 'general2D') {
        invokeCmd(cmdSeed, null, { editType: 'increaseAndDecrease' });
      }
    }
  };
  const uiSchema: UiSchema = {
    SelectedEntities: {
      'ui:field': 'entity',
      pickTypes,
    },
  };
  return (
    <CommandDialog2
      title={title}
      formData={formData}
      schema={schema}
      extraUiSchema={uiSchema}
      liveValidate
      onClose={onClose}
      onSubmit={onSubmit}
      submitLoading={loading}>
      <MeshDialogFooter onCancel={onClose} />
    </CommandDialog2>
  );
}
